// 服务端程序：
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<netinet/in.h>

int main(){

	int sfd = socket(AF_INET,SOCK_STREAM,0);
	if(sfd<0){
		perror("socket error");
		return -1;
	}
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr("127.0.0.1");
	addr.sin_port = 8888;
	int ret = bind(sfd,(struct sockaddr *)&addr,sizeof(addr)); // 绑定套接字 socket;
	if(ret<0){
		perror("bind error:");
		goto errout;
	}
	ret = listen(sfd,64);
	// 监听连接请求同时最大的连接队列设置为64；
	if(ret<0){
		perror("listen error:");
		goto errout;
	}
	int cfd = accept(sfd,NULL,NULL);
	// 接受客户端连接请求，不保留客户端的套接字信息；
	int n=0;
	char buf[256];
	char sendstr[300];
	for(;;){
		memset(buf,0x00,sizeof(buf));
		memset(sendstr,0x00,sizeof(sendstr));
		// n = recv(sfd,buf,sizeof(buf),0);
		n = read(cfd,buf,sizeof(buf));
		if(n<=0){
			printf("recv data stream end, now recv byte=[%d]\n",n);
			break;
		}
		printf("client send msg: %s\n",buf);
		snprintf(sendstr,sizeof(sendstr),"server echo:%s\n",buf);
		write(cfd,sendstr,strlen(sendstr));
	}
normout:
	close(cfd);
	close(sfd);
	return 0;
	
errout: 
	close(sfd);
	return -1;

}




